package com.mamingchao.basic.function_object;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Comparator.comparing;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.*;

/**
 * 优先选择Stream 中无副作用的函数
 * Created by mamingchao on 2021/1/13.
 */
public class Collect {

    public static void main(String[] args) throws IOException{
        //version 1
        //模拟一个 词汇列表 ,
        List<String> words = new ArrayList<>();
        Stream<String> words1 = Stream.of(new String[]{"ma","ming","chang","ma","ma","mu","xiao","lin","lin","mu"});
        Stream<String> words2 = Arrays.stream(new String[10]);

        //统计每个词汇出现的频率
        Map<String,Long> freq = new HashMap<>();

        //这是伪装成 lambda 表达式的 做法，其实不是
        //因为在lambda 表达式中用了外部资源 freq
        //其中 Map.merge 这个操作:第一个参数是key；如果key 不存在或者 对应的值是null，第二个参数给该key赋值
        //如果key对应的value 不是空，就用第三个 函数引用 计算一下新的value，跟该key对应上；如果 计算后的新的值
        //还是空，remove掉这个key
//        words.forEach(word -> freq.merge(word, 1L ,Long::sum));
//        words1.forEach(word -> freq.merge(word, 1L ,Long::sum));
//        words2.forEach(word -> freq.merge(word, 1L ,Long::sum));



        //version 2
        //这个是 真正的lambda 表达式
        Map<String,Long> freq1 = words1.collect(groupingBy(String::toLowerCase,counting()));


        //version 3
        //统计出现频率排名前10的词汇
        List<String> top3 = freq1.keySet().stream().sorted(comparing(freq1::get).reversed()).limit(3).collect(toList());

        //toMap

        words1.close();
        words2.close();
        System.out.println();


    }
}
